package controller

import (
	"encoding/json"
	"fmt"
	"gin/common"
	"gin/model"
	"gin/response"
	"gin/util"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"strconv"
	"time"
)

// AddressList 地址列表
func Test(ctx *gin.Context) {
	user := ctx.Query("user")
	fmt.Println(user)
	var list []*model.AddressInfo
	Db := common.GetDB()
	Db.Debug().Table("cat_meal_address").Where("uid =?", user).Find(&list)
	var a []ChUser
	Db.Debug().Table("chat_demo.ch_user").Where("id =?", 1).Find(&a)
	fmt.Println(a)
	response.Success(ctx, gin.H{"list": list}, "success")
	response.Success(ctx, gin.H{"list": a}, "success")
}

type ChUser struct {
	Id       int    `json:"id"`
	UserName string `json:"user_name"`
	Password string `json:"password"`
	Nickname string `json:"nickname"`
}

// Register 注册
func Register(ctx *gin.Context) {
	name := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号格式有误"})
		return
	}
	var isTelephoneExist = model.IsTelephoneExist(common.GetDB(), telephone)
	if isTelephoneExist == true {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号格已注册"})
		return
	}
	if len(password) < 6 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码格式有误"})
		return
	}
	//加密
	hasdPwd, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "密码格式有误"})
		return
	}
	if len(name) == 0 {
		name = util.RandomString(10)
	}
	DB := common.GetDB()
	newUser := model.User{
		Password:  string(hasdPwd),
		Name:      name,
		Telephone: telephone,
	}
	DB.Create(newUser)
	ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "注册成功"})
	return
}

// Login 登录
func Login(ctx *gin.Context) {
	name := ctx.PostForm("name")
	password := ctx.PostForm("password")
	if len(password) < 6 {
		response.Fail(ctx, nil, "密码格式有误")
		return
	}

	var user model.User
	DB := common.GetDB()
	DB.Table("users").Where("name=?", name).Or("telephone=?", name).First(&user)

	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		response.Fail(ctx, nil, "密码错误")
		return
	}
	/*	token, err := common.ReleaseToken(user.ID)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{"msg": err})
			log.Printf("token 失败原因 ： %v", err)
			return
		}*/
	//response.Success(ctx, gin.H{"token": token, "info": dto.ToUserDto(user)}, "success")
	return

}

// Info 个人信息
func Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	DB := common.GetDB()
	var sumArr []float64
	DB.Debug().Table("cat_meal_order").Where("uid =? and status =3", user.(model.UserInfo).Uid).Pluck("COALESCE(SUM(amountReal),0) as amount", &sumArr)
	sum := sumArr[0]
	var level []model.LevelInfo
	DB.Debug().Table("cat_meal_level").Find(&level)
	var userLevel = 0
	if sum > 0 {
		for _, v := range level {
			if sum > v.UpgradeAmount {
				userLevel = v.Id
			}
		}
		if user.(model.UserInfo).Level < userLevel {
			DB.Debug().Table("cat_meal_user").Where("uid = ?", user.(model.UserInfo).Uid).Update("level", userLevel)
		}
	}
	var count int
	DB.Debug().Table("cat_meal_user_coupons").Where(" uid=? and status=1", user.(model.UserInfo).Uid).Count(&count)
	user1 := model.OpenidGetUser(common.GetDB(), user.(model.UserInfo).Openid)
	response.Success(ctx, gin.H{"info": user1, "totalConsumed": sum, "levelList": level, "userLevel": userLevel, "couponsCount": count}, "success")
}

func getReturnInfo(user model.UserInfo, token string) (model.UserInfo, string) {
	redisDB := common.GetRedis()
	user.Token = ""
	model.UpdateLastLogin(common.GetDB(), user, token)
	bjson, err := json.Marshal(user)
	if err != nil {
		fmt.Println("Umarshal failed:", err)
		return user, token
	}
	redisDB.Set("UID"+strconv.Itoa(user.Uid), bjson, time.Second*30*24*60*60)
	return user, token
}

func GetScoreList(ctx *gin.Context) {
	Type := ctx.PostForm("type")
	if len(Type) == 0 {
		Type = ""
	} else {
		Type = "type = " + Type
	}

	page := ctx.PostForm("page")
	if len(page) == 0 {
		page = "0"
	}
	p, _ := strconv.Atoi(page)
	var site = 10
	offset := (p - 1) * site
	Db := common.GetDB()
	user, _ := ctx.Get("user")
	var scoreList []model.ScoreStruct
	Db.Debug().Table("cat_meal_user_score").
		Where("uid=? ", user.(model.UserInfo).Uid).Where(Type).Order("id desc").
		Limit(site).Offset(offset).Find(&scoreList)
	var count int64
	Db.Debug().Table("cat_meal_user_score").Where("uid=? ", user.(model.UserInfo).Uid).Where(Type).Count(&count)
	response.Success(ctx, gin.H{"list": scoreList, "page_site": site, "page_no": p + 1, "count": count}, "success")
}

func GetRecommendList(ctx *gin.Context) {
	Db := common.GetDB()
	user, _ := ctx.Get("user")
	var List []model.UserInfo
	Db.Debug().Table("cat_meal_user").Where("agent_id=? ", user.(model.UserInfo).Uid).Order("uid desc").Find(&List)
	var count int64
	Db.Debug().Table("cat_meal_user").Where("agent_id=? ", user.(model.UserInfo).Uid).Count(&count)
	response.Success(ctx, gin.H{"list": List, "count": count}, "success")
}
